/**
 * 用于生成slidbar
 * Created by Administrator on 2016/1/27.
 */

(function ($) {
    "use strict";
    moment.locale("zh-cn");
    var mainContent = $("#page-content");
    var selectId, table, selectRow, detailTable, lastLoadFxid;
    var map;


    /**
     * 初始化表格
     */
    function aceSwitch(cellvalue, options, cell) {
        setTimeout(function () {
            $(cell).find('input[type=checkbox]')
                .addClass('ace ace-switch ace-switch-5')
                .after('<span class="lbl"></span>');
        }, 0);
    }

    function updatePagerIcons(table) {
        var replacement =
        {
            'ui-icon-seek-first': 'ace-icon fa fa-angle-double-left bigger-140',
            'ui-icon-seek-prev': 'ace-icon fa fa-angle-left bigger-140',
            'ui-icon-seek-next': 'ace-icon fa fa-angle-right bigger-140',
            'ui-icon-seek-end': 'ace-icon fa fa-angle-double-right bigger-140'
        };
        $('.ui-pg-table:not(.navtable) > tbody > tr > .ui-pg-button > .ui-icon').each(function () {
            var icon = $(this);
            var $class = $.trim(icon.attr('class').replace('ui-icon', ''));

            if ($class in replacement) icon.attr('class', 'ui-icon ' + replacement[$class]);
        })
    }

    function enableTooltips(table) {
        $('.navtable .ui-pg-button').tooltip({container: 'body'});
        $(table).find('.ui-pg-div').tooltip({container: 'body'});
    }

    /**
     * 初始化日期选择控件
     */
    var initDatepicker = function () {
        $('.date-picker').datepicker({
                startView: 1,
                minViewMode: 1,
                maxViewMode: 1,
                autoclose: true,
                language: 'zh-CN',
                todayHighlight: true
            })
            //show datepicker when clicking on the icon
            .next().on(ace.click_event, function () {
            $(this).prev().focus();
        });
    };

    /**
     * 读取风险详情
     * @param id
     */
    var loadInfo = function (id) {
        $.request(
            $.router.server + "repm/find",
            {
                "type": "post",
                "data": {
                    replyId: id
                },
                "callback": function (data) {
                    for (var i in data) {
                        var d = data[i];
                        for (var j in d) {
                            $("#st2_" + j).val(d[j])
                        }
                    }
                    //$("#st2_filename").html(data[2]["filename"]);
                    //$("#st2_filename").attr("href", $.router.server+"encl/download?id=" + data[2]["id"]);
                    $("#st2_rpid").val(data[0]["id"]);
                    $("#st2_hcsj").val(moment($("#st2_hcsj").val(), "mm-dd-yyyy").format("YYYY-MM"));
                }
            }
        )
    };
    var initSelect = function(){
        var selectArea = $("#form-select");
        selectArea.empty();
        $.post($.router.server + "dataMart/table",function(data){
            $.each(data,function(i,d){
            	var $op = $("<option value='"+d.tableName+"'>"+d.tableName+"</option>");
            	$op.data("mart",d);
            	 selectArea.append($op);
            });
            $('.chosen-select').chosen({allow_single_deselect:true});
            initGrid();
        });
    };

    /**
     * 初始化风险列表
     */
    var initGrid = function () {
    	//destory
    	$("#log-grid-table").jqGrid('GridDestroy', 'log-grid-table');
    	$("#log-data").empty();
    	$("#log-data").html('<table id="log-grid-table"></table><div id="log-grid-pager"></div>');
        var dataMarket = $("#form-select option:selected").data("mart");
        selectId = null;
        selectRow = null;
        var grid_selector = "#log-grid-table";
        var pager_selector = "#log-grid-pager";
        $(window).on('resize.jqGrid', function () {
            $(grid_selector).jqGrid('setGridWidth', $("#step-container").width());
        });
        //resize on sidebar collapse/expand
        var parent_column = $(grid_selector).closest('[class*="col-"]');
        $(document).on('settings.ace.jqGrid', function (ev, event_name, collapsed) {
            if (event_name === 'sidebar_collapsed' || event_name === 'main_container_fixed') {
                $(grid_selector).jqGrid('setGridWidth', parent_column.width());
            }
        });
        var columns = dataMarket["columns"],
            colNames = [],
            colModel = [];
        colNames.push("操作");
        colModel.push({
            "name": "cz",
            "width":120,
            "resize": false,
            formatter:function(data,row,rs,e){
                var tableName = dataMarket.tableName;
                return [
                    '<button class="btn btn-primary log-action" data-name="'+tableName+'" data-id="' + rs.ZX_ID + '">',
                    '<i class="ace-icon glyphicon  align-top bigger-125"></i>',
                    '核查',
                    '</button>'
                ].join("");
            }
        });
        for (var i in columns) {
            if(!columns.hasOwnProperty(i)){
                continue;
            }
            colNames.push(columns[i]["label"]);
            if( columns[i]["name"]=='ZX_STATUS'){
                colModel.push({
                    "name": columns[i]["name"],
                    "width":120,
                    "resize": false,
                    formatter: function (data) {
                        if (data == '1') {
                            return "已核查";
                        }
                        return "未核查";
                    }
                })
            }else{
                colModel.push({
                    "name": columns[i]["name"],
                    "width":120,
                    "resize": false
                })
            }

        }

        $(grid_selector).jqGrid({
            url: $.router.server + "dataMart/page",
            mtype: "POST",
            headertitles:true,
            postData: {
                "tableName": dataMarket.tableName
            },
            datatype: "json",
            height: 200,
            colNames: colNames,
            colModel: colModel,
            repeatitems: false,
            jsonReader: {
                root: "datas",    // json中代表实际模型数据的入口
                page: "page",    // json中代表当前页码的数据
                total: "pageCount",    // json中代表页码总数的数据
                records: "total" // json中代表数据行总数的数据
            },
            viewrecords: true,
            rowNum: 10,
            pager: pager_selector,
            altRows: true,
            multiselect: false,
            //multikey: "ctrlKey",
            multiboxonly: false,

            loadComplete: function () {
                var table = this;
                setTimeout(function () {

                    updatePagerIcons(table);
                    enableTooltips(table);
                }, 0);
            },
            onSelectRow: function (id) {
                selectId = id;
                selectRow = $(this).jqGrid('getRowData', id);
            }
            //, autowidth: true

        });
        table = $(grid_selector);
        $(window).triggerHandler('resize.jqGrid');
    };


    var pageReady = function () {
        initSelect();
        $("#form-select").on("change",function(){
            initGrid();
        });


    };
    //数据核查操作
    var hc = function(){
        var tableName = $(this).data("name");
        var hcId = $(this).data("id");
        $.post($.router.server + "dataMart/hc",{
            "tableName":tableName,
            "hcId":hcId
        },function(data){
            table.trigger("reloadGrid");
            showResultBox(data.message);
        });
    }
    mainContent.on("pageshow.0401", function () {
        if (mainContent.find("[data-page=log-page]").length > 0) {
            pageReady();
        }
    });
    var showResultBox = function(message){
        var dialog = bootbox.dialog({
                title: "处理结果",
                size: "large",
                message:message
            }
        ).init(function () {
                $('.modal-dialog').css({
                    width:"80%"
                });
                $('.modal-body').css({
                    overflow:"auto"
                });
            });
    };
    $(document).on("click.log-action",".log-action",hc);
})(jQuery);
